#include "head.h"

// 日志级别
// typedef enum {
//     DEBUG,
//     INFO,
//     WARN,
//     ERROR
// } log_level;

// 获取当前时间字符串
char *get_current_time() {
    time_t now = time(NULL);
    struct tm *tm_now = localtime(&now);
    char *time_str = malloc(20);
    if (time_str == NULL) {
        perror("malloc failed");
        return NULL;
    }
    memset(time_str, 0, 20);
    // 将时间字符串格式化为"YYYY-MM-DD HH:MM:SS"格式
    strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", tm_now);
    return time_str;
}

// 写日志到文件
void write_log(log_level level, const char *msg, const char *filename, const char *funcname, int line, const char *username, const char *action) {
    int fd = open("server.log", O_WRONLY | O_APPEND | O_CREAT, 0644);
    if (fd == -1) {
        perror("open logfile failed");
        return;
    }
    char *time_str = get_current_time();
    char *level_str = NULL;
    switch (level) {
        case DEBUG:
            level_str = "DEBUG";
            break;
        case INFO:
            level_str = "INFO";
            break;
        case WARN:
            level_str = "WARN";
            break;
        case ERROR:
            level_str = "ERROR";
            break;
        default:
            level_str = "UNKNOWN";
            break;
    }
    // 将time_str和level_str和msg拼接成一个字符串
    // 额外添加20个字节的空间来容纳日志分隔符和换行符等
    char *log_str = malloc(strlen(time_str) + strlen(level_str) + strlen(msg) + strlen(filename) + strlen(funcname) + sizeof(int) + strlen(username) + strlen(action) + 20);
    if (log_str == NULL) {
        perror("malloc failed");
        return;
    }
    sprintf(log_str, "[%s] [%s] %s %s %d [%s] \"%s\" \"%s\"\n", time_str, level_str, filename, funcname, line, username, action, msg);
    // 将log_str写入文件
    write(fd, log_str, strlen(log_str));

    close(fd);
    free(log_str);
    free(time_str);
}

// 测试文件testlog.c

// #include "head.h"

// int main(void) {
//     LOG(DEBUG, "xz", "sendfile", "sendfile success");
//     LOG(DEBUG, "xz", "sendfile", "sendfile success");
//     return 0;
// }

// 编译命令: gcc testlog.c log.c -o testlog
// ./testlog
